package hoyo.zqy.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import hoyo.zqy.basic.contant.WxConstants;
import hoyo.zqy.basic.dto.LoginDto;
import hoyo.zqy.basic.exception.BusinessException;
import hoyo.zqy.basic.jwt.JwtUtils;
import hoyo.zqy.basic.jwt.LoginData;
import hoyo.zqy.basic.jwt.RsaUtils;
import hoyo.zqy.basic.util.AjaxResult;
import hoyo.zqy.basic.util.HttpUtil;
import hoyo.zqy.basic.util.Md5Utils;
import hoyo.zqy.basic.util.StrUtils;
import hoyo.zqy.org.mapper.EmployeeMapper;
import hoyo.zqy.system.domain.Menu;
import hoyo.zqy.user.domain.Logininfo;
import hoyo.zqy.user.domain.User;
import hoyo.zqy.user.domain.Wxuser;
import hoyo.zqy.user.mapper.LogininfoMapper;
import hoyo.zqy.user.mapper.UserMapper;
import hoyo.zqy.user.mapper.WxuserMapper;
import hoyo.zqy.user.service.ILogininfoService;
import hoyo.zqy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //获取参数
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();
        //空值校验
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(checkPass)){
            throw new BusinessException("页面正在自爆中");
        }
        //校验账号
        Logininfo logininfo =  logininfoMapper.loadByAccount(loginDto);
        if (logininfo==null){
            throw new BusinessException("账号或者密码错误");
        }
        //校验密码
        String md5 = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if (!md5.equals(logininfo.getPassword())){
            throw new BusinessException("账号或者密码错误");
        }
        //用户是否被禁用
        if (!logininfo.getDisable()){
            throw new BusinessException("账号已封禁");
        }
        //登录成功调用jwt方法，生成token响应给前端
        Map<String,Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }
    //微信三方登录
    @Override
    public AjaxResult wechatLogin(String code) {
        //组装请求地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET).replace("CODE",code);
        //使用HTTP工具类发送请求获取json格式字符串
        String jsonStr = HttpUtil.httpGet(url);
        //将json格式字符串转化为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //3.根据openid去查询t_wxuser表
        Wxuser wxuser = wxuserMapper.findByOpenid(openId);
        //如果通过openid查询到了微信用户对象
        if (wxuser!=null){
            User user = userMapper.loadById(wxuser.getUserId());
            //如果user表也注册了
            if (user!=null){
                //就免密登录
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                //登录成功调用jwt方法，生成token响应给前端
                Map<String,Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
        String parmas = "?accessToken="+accessToken+"&openid="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(parmas);
    }

    /**
     * 设置私钥
     * @param logininfo
     * @return
     */
    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        //生成map接受数据返回
        Map<String,Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        map.put("logininfo", logininfo);
        loginData.setLogininfo(logininfo);
        //判断是否是管理员
        if (logininfo.getType()==0){
            //获取当前等录人权限
            List<String> permissions = employeeMapper.getPermissionByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //获取当前等两人的菜单
            List<Menu> menus = employeeMapper.getMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        try {
            //将以上三个数据装到LoginData  - 使用工具类进行加密【1 2】 - jwt串
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //使用工具类私钥进行加密
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 60*24*7);
            //存入map
            map.put("token",jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        //获取参数
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openid = map.get("openid");
        //空值校验
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("请输入电话或密码");
        }
        //手机验证码校验
        Object codeTmp = redisTemplate.opsForValue().get("binder:"+ phone);
        if (codeTmp==null){
            throw new BusinessException("请输入有效验证码");
        }
        String code = ((String)codeTmp).split(":")[0];
        //验证码不要区分大小写
        if(!verifyCode.equalsIgnoreCase(code)){
            throw new BusinessException("验证码错误!!!");
        }
        //组装第三个请求地址
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
        //通过token和openID发送第三个请求，返回JSON格式字符串
        String jsonStr = HttpUtil.httpGet(url);
        //使用fastJSON将json格式的字符串转成json对象，再转成一个WxUser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr); //user_id
        //先通过openID去找t_wxuser，如果有直接删除
        Wxuser wx = wxuserMapper.findByOpenid(openid);
        if (wx!=null){
            wxuserMapper.delete(wx.getId());
        }
        //创建一个user对象
        User user = userMapper.loadByPhone(phone);
        if (user==null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            //添加logininfo
            logininfoMapper.save(logininfo);
            //添加user
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //添加WxUser对象到数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        //登录成功调用jwt方法，生成token响应给前端
        Map<String,Object> maps = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(maps);
    }

    /**
     * logininfo赋值
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo );
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    /**
     * user赋值
     * @param phone
     * @return
     */
    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(6);
        String md5 = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        user.setState(1);
        return user;
    }

    /**
     * 微信数据获取
     * @param jsonStr
     * @return
     */
    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
